package com.zy.service.crm.impl;


import java.util.List;
import java.util.Objects;

import com.zy.dao.bs.CarDao;
import com.zy.dao.bs.ClubDao;
import com.zy.dao.bs.CustomerClubDao;
import com.zy.dao.crm.CustomerInfoDao;
import com.zy.entity.bs.Car;
import com.zy.entity.bs.Club;
import com.zy.entity.bs.CustomerClub;
import com.zy.entity.crm.CustomerInfo;
import com.zy.utils.CodeUtil;
import com.zy.utils.PropertiesUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zy.dao.crm.CustomerDao;
import com.zy.dao.redis.RedisRepository;
import com.zy.dao.sys.UserDao;
import com.zy.dao.sys.UserRoleDao;
import com.zy.entity.crm.Customer;
import com.zy.entity.enums.StatusEnum;
import com.zy.entity.sys.User;
import com.zy.entity.sys.UserRole;
import com.zy.pojo.constants.Constant;
import com.zy.pojo.exceptions.ControllerException;
import com.zy.pojo.exceptions.ExceptionEnum;
import com.zy.pojo.exceptions.ServiceException;
import com.zy.pojo.query.crm.CustomerQuery;
import com.zy.pojo.vos.common.PageVo;
import com.zy.service.base.impl.BaseServiceImpl;
import com.zy.service.crm.CustomerService;
import com.zy.utils.DateUtil;
import com.zy.utils.MD5Util;

import tk.mybatis.mapper.entity.Example;

@Service("customerService")
public class CustomerServiceImpl extends BaseServiceImpl<Customer> implements CustomerService {

	@Autowired
	private CustomerDao customerDao;

	@Autowired
	private ClubDao clubDao;

	@Autowired
	private UserRoleDao userRoleDao;
	@Autowired
	private CustomerClubDao customerClubDao;
	@Autowired
	private RedisRepository redisRepository;
	@Autowired
	private UserDao userDao;
	@Autowired
	private CarDao carDao;
	@Autowired
	private CustomerInfoDao customerInfoDao;

	@Override
	public PageVo pageCustomer(CustomerQuery customerQuery, int start, int limit) {
		return new PageVo(start, limit, this.customerDao.countCustomer(customerQuery),
				this.customerDao.listCustomer(customerQuery, start, limit));
	}

	@Override
	public void saveCustomer(Customer customer) {
		customer.setId(null);
		long time = DateUtil.getTime();
		customer.setCreateTime(time);
		customer.setModifyTime(time);
		customer.setStatus(StatusEnum.NORMAL.getValue());
		this.customerDao.save(customer);
	}

	@Override
	public void removeCustomer(long id) {
		try {
			this.customerDao.removeByPrimaryKey(id);
		} catch (Exception e) {
			log.info(e.getMessage(), e);
			Customer customer = new Customer();
			customer.setId(id);
			customer.setModifyTime(DateUtil.getTime());
			customer.setStatus(StatusEnum.DELETE.getValue());
			this.customerDao.updateByPrimaryKeySelective(customer);
		}
	}

	@Override
	public void recover(long id) {
		Customer customer = new Customer();
		customer.setId(id);
		customer.setModifyTime(DateUtil.getTime());
		customer.setStatus(StatusEnum.NORMAL.getValue());
		this.customerDao.updateByPrimaryKeySelective(customer);
	}

	@Override
	public String getCustomerName(Long id) {
		return customerDao.getByPrimaryKey(id).getCustomerName();
	}

	@Override
	public void updateCustomer(Customer customer) {
		Example ex = new Example(CustomerInfo.class);
		ex.createCriteria().andEqualTo("customerId",customer.getId());
		CustomerInfo cu = new CustomerInfo();
		BeanUtils.copyProperties(customer,cu,"id");
		cu.setCustomerId(customer.getId());
		this.customerInfoDao.updateByExampleSelective(cu,ex);
		customerDao.updateByPrimaryKeySelective(customer);
	}

	@Override
	public void saveCustomerUser(User user) {
		String moilde = user.getMobile();
		Example ex = new Example(User.class);
		ex.createCriteria().andEqualTo("mobile", moilde);
		if (userDao.getCountByExample(ex) > 0) {
			throw new ServiceException("该手机号已注册");
		}
		String salt = CodeUtil.getUniqueCode();
		user.setSalt(salt);
		user.setUserName(moilde);
		user.setSalt(salt);
		user.setUserPwd(MD5Util.getMD5Pwd(salt, user.getUserPwd()));
		user.setStatus(StatusEnum.NORMAL.getValue());
		userDao.save(user);

		UserRole userRole = new UserRole();
		userRole.setUserId(user.getId());
		userRole.setRoleId(Constant.MEMEBER_ROLE_ID);
		userRoleDao.save(userRole);

		Customer cutomer = new Customer();
		cutomer.setUserId(user.getId());
		cutomer.setUserName(moilde);
		cutomer.setMobile(moilde);
		customerDao.save(cutomer);




	}

	@Override
	public Customer getCustomerByUserId(long userId) {
		return this.customerDao.getCustomerByUserId(userId);
	}

	@Override
	public void updatePayPsw(Long id, String newPsw, String pswRe, String mobileCode) {
		if (!MD5Util.getMD5(newPsw).equals(MD5Util.getMD5(pswRe))) {
			throw new ServiceException("输入支付密码不一致");
		}
		Customer customer = getByPrimaryKey(id);
		String psw = customer.getPayPsw();
		if (!StringUtils.isEmpty(psw)) {
			if (psw.equals(MD5Util.getMD5(newPsw))) {
				throw new ServiceException("与原支付密码相同");
			}
		}
		User user = userDao.getByPrimaryKey(customer.getUserId());
//		String mobileCodeKey = Constant.VALIDCODE + user.getMobile();
//		if (!this.redisRepository.exist(mobileCodeKey)) {
//			throw new ServiceException(ExceptionEnum.MOBILE_VALID_NOT_EXISTS);
//		}
//		if (!((String) this.redisRepository.get(mobileCodeKey)).equalsIgnoreCase(mobileCode)) {
//			throw new ControllerException(ExceptionEnum.MOBILE_VALID_CODE_ERROR);
//		}
		customer.setPayPsw(MD5Util.getMD5(newPsw));
		customerDao.updateByPrimaryKey(customer);

	}

	@Override
	public boolean whetherSetPayPsw(Long id) {
		Customer customer = customerDao.getByPrimaryKey(id);
		if (!StringUtils.isEmpty(customer.getPayPsw())) {
			return true;
		}
		return false;
	}

	@Override
	public boolean isCheckPass(Long customerId, String moilde, String payPsw, String code) {
		Customer customer = customerDao.getByPrimaryKey(customerId);
		User user = userDao.getByPrimaryKey(customer.getUserId());
		if (user.getMobile().equals(moilde)) {
			throw new ServiceException("手机号未发生变动");
		}
		Example ex = new Example(User.class);
		ex.createCriteria().andEqualTo("mobile", moilde);
		if (userDao.getCountByExample(ex) > 0) {
			throw new ServiceException("该手机号已注册");
		}
		String mobileCodeKey = Constant.VALIDCODE + moilde;
		if (!this.redisRepository.exist(mobileCodeKey)) {
			throw new ServiceException(ExceptionEnum.MOBILE_VALID_NOT_EXISTS);
		}
		if (!((String) this.redisRepository.get(mobileCodeKey)).equalsIgnoreCase(code)) {
			throw new ControllerException(ExceptionEnum.MOBILE_VALID_CODE_ERROR);
		}

		if (!MD5Util.getMD5(payPsw).equals(customer.getPayPsw())) {
			throw new ServiceException("支付密码不正确");
		}
		redisRepository.delete(mobileCodeKey);
		return true;
	}

	@Override
	public Customer webGetCustomer(Long id) {
		return customerDao.getByPrimaryKey(id);
	}

	@Override
	public Customer getCurrentCustomerInfo(long id) {
		return customerDao.getCurrentCustomerInfo(id);
	}
	@Override
	public void cancelBind(Long id,Long userId) {
		Customer customer = customerDao.getByPrimaryKey(id);
		UserRole userRole = new UserRole();
		userRole.setUserId(customer.getUserId());
		userRoleDao.remove(userRole);
		CustomerClub cc = new CustomerClub();
		cc.setClubId(2L);
		cc.setCustomerId(id);
		customerClubDao.remove(cc);
		Example ex = new Example(CustomerClub.class);
		ex.createCriteria().andEqualTo("customerId",id);
		long count = customerClubDao.getCountByExample(ex);
		if(count==0){
			userDao.removeByPrimaryKey(userId);
		}


	}

	@Override
	public List<Club> getClubList(long customerId) {
		return clubDao.getClubList(customerId);
	}

	@Override
	public boolean hasClub(Long customerId) {
		if(CollectionUtils.isEmpty(getClubList(customerId))){
			return false;
		}
		return true;
	}

    @Override
    public void joinCustomer(Customer customer) {
//		User user = new User();
//		String salt = CodeUtil.getUniqueCode();
//		user.setSalt(salt);
//		user.setUserName(customer.getMobile());
//		user.setSalt(salt);
//		user.setUserPwd(MD5Util.getMD5Pwd(salt, PropertiesUtil.getConfigProperty("user.resetPwd")));
//		userDao.save(user);
//
//		long time = DateUtil.getTime();
//		Example ex = new Example(User.class);
//		ex.createCriteria().andEqualTo("mobile", customer.getMobile());
//		if (userDao.getCountByExample(ex) > 0) {
//			throw new ServiceException("该手机号已注册");
//		}
//		customer.setStatus(StatusEnum.NORMAL.getValue());
//		customer.setCreateTime(time);
//		customer.setModifyTime(time);
//		customer.setUserId(user.getId());
//		this.customerDao.save(customer);
//		Car car = new Car();
//		BeanUtils.copyProperties(customer,car,"id");
//		existsName(car);
//		car.setCustomerId(customer.getId());
//		carDao.save(car);
//		CustomerInfo customerInfo = new CustomerInfo();
//		BeanUtils.copyProperties(customer,customerInfo,"id");
//		customerInfo.setCustomerId(customer.getId());
//		customerInfoDao.save(customerInfo);

    }

    @Override
    public Customer updateCustomerApp(Customer customer) {
        Example ex = new Example(CustomerInfo.class);
        ex.createCriteria().andEqualTo("customerId",customer.getId());
        CustomerInfo cu =customerInfoDao.getByExample(ex);
        customer.setStatus(StatusEnum.NORMAL.getValue());
        customerDao.updateByPrimaryKeySelective(customer);
        if(Objects.isNull(cu)){
            cu = new CustomerInfo();
            cu.setCustomerId(customer.getCustomerId());
            cu.setBirthDate(customer.getBirthDate());
            cu.setSex(customer.getSex());
            cu.setNikeName(customer.getNikeName());
            cu.setCustomerId(customer.getCustomerId());
            cu.setCustomerName(customer.getCustomerName());
            cu.setCustomerId(customer.getCustomerId());
            cu.setSignature(customer.getSignature());
            this.customerInfoDao.save(cu);
        }else{
            cu.setBirthDate(customer.getBirthDate());
            cu.setSex(customer.getSex());
            cu.setNikeName(customer.getNikeName());
            cu.setCustomerId(customer.getCustomerId());
            cu.setCustomerName(customer.getCustomerName());
            cu.setCustomerId(customer.getCustomerId());
            cu.setSignature(customer.getSignature());

            this.customerInfoDao.updateByPrimaryKeySelective(cu);
        }




        return customerDao.customerInfo(customer.getId());
    }

    @Override
    public Customer customerInfo(Long id) {
        return customerDao.customerInfo(id);
    }


}
